package jdbc.day2.demo1_事务;

import tmp.DBUtil;
import tmp.Tmp;

import java.sql.Connection;
import java.sql.Statement;

public class MyTransac {
    public static void main1(String[] args)throws Exception {
        Connection con= DBUtil.getConnection();
        Statement st=con.createStatement();
        //开启事务，本质上是关闭自动提交
        try{
            con.setAutoCommit(false);
            //并不写磁盘，而是写入缓存
            st.executeUpdate("insert into stu (s_id,sname) values(8,'b1')");
            st.executeUpdate("insert into stu (s_id,sname) values(9,'b2')");
            //把写入缓存中数据写入磁盘
            con.commit();
        }catch (Exception e){
            con.rollback();
        }finally {
            con.setAutoCommit(true);
            DBUtil.close(con,st,null);
        }

    }
    public static void main(String[] args)throws Exception {
        Connection con= DBUtil.getConnection();//c1
        //开启事务，本质上是关闭自动提交
        try{
            con.setAutoCommit(false);//c1
            //并不写磁盘，而是写入缓存
            Tmp.update("insert into stu (s_id,sname) values(?,?)",10,"b3");
            Tmp.update("insert into stu (s_id,sname) values(?,?)",10,"b4");//c2

            //把写入缓存中数据写入磁盘
            con.commit();//c1
        }catch (Exception e){
            e.printStackTrace();
            con.rollback();//c1
        }finally {
            con.setAutoCommit(true);//c1
            DBUtil.close(con,null,null);
        }
    }
}
